package com.shanxia.codec.cmd;

import com.shanxia.codec.ProtocolDataBase;
import com.shanxia.codec.enums.DecodeEnum;
import lombok.Data;

import java.util.Arrays;

import static com.shanxia.codec.Decoder.*;

/**
 * S -> C
 * 服务器对充电桩登入应答
 * 回复充电桩接下来的报文加密方式
 */
@Data
public class Cmd1201 extends ProtocolDataBase {

    public static final int MIN_SIZE = 32;

    private int v1;
    private int v2;
    private int encryptionSign;             // AES密钥标志
    private String aesSecretKey;            // 后续报文 AES 加密密钥

    public Cmd1201(){
        super.setCmd(1201);
    }

    public static Cmd1201 decodeFromBase(ProtocolDataBase protocolDataBase) {
        Cmd1201 cmd = new Cmd1201();
        cmd.copyDataFrom(protocolDataBase);
        byte[] dataField = protocolDataBase.getDataField();
        if (dataField.length < MIN_SIZE) {
            cmd.setResult(DecodeEnum.InvalidData);
            return cmd;
        }
        int offset = 0;
        cmd.v1 = getUint16(dataField, offset);
        offset += 2;
        cmd.v2 = getUint16(dataField, offset);
        offset += 2;
        // 4字节AES密钥标志
        cmd.encryptionSign = bytesToIntLittle(dataField, offset);
        offset += 4;
        // 24字节后续报文 AES 加密密钥
        cmd.aesSecretKey = byteToAscii(Arrays.copyOfRange(dataField, offset, offset + 24), false);
        return cmd;
    }

    @Override
    public byte[] getDataField() {
        byte[] data = new byte[MIN_SIZE];
        int offset = 0;
        getBytesAsUint16(data, offset, this.v1);
        offset += 2;
        getBytesAsUint16(data, offset, this.v2);
        offset += 2;
        // 4字节AES密钥标志
        intToBytesLittle(data, offset, encryptionSign);
        offset += 4;
        // 24字节后续报文 AES 加密密钥
        encodeAscii(data, aesSecretKey, 24, offset);
        return data;
    }
}
